package com.hurt.competition.judge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hurt.competition.admin.dto.CompetitionReq;
import com.hurt.competition.admin.model.Competition;
import com.hurt.competition.admin.service.CompetitionService;
import com.hurt.competition.common.enums.JudgeStateEnum;
import com.hurt.competition.common.exception.CoreException;
import com.hurt.competition.common.vo.PageResult;
import com.hurt.competition.judge.dto.CompetitionJudgeListRes;
import com.hurt.competition.judge.dto.CompetitionJudgeReq;
import com.hurt.competition.judge.mapper.CompetitionJudgeMapper;
import com.hurt.competition.judge.model.CompetitionJudge;
import com.hurt.competition.judge.service.CompetitionJudgeService;
import com.hurt.competition.player.model.SysUser;
import com.hurt.competition.player.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CompetitionJudgeServiceImpl extends ServiceImpl<CompetitionJudgeMapper, CompetitionJudge> implements CompetitionJudgeService {

    @Autowired
    private CompetitionService competitionService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void apply(CompetitionJudge competitionJudge) {
        LambdaQueryWrapper<CompetitionJudge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CompetitionJudge::getCompetitionId,competitionJudge.getCompetitionId())
                .eq(CompetitionJudge::getUserId,competitionJudge.getUserId());

        if(getOne(queryWrapper)!=null){
            throw new CoreException("该用户已申请或已成为该比赛的评委");
        }

        competitionJudge.setState(JudgeStateEnum.APPLY.getCode());
        save(competitionJudge);
    }

    @Override
    public PageResult<CompetitionJudgeListRes> queryList(CompetitionJudgeReq req) {
        PageResult pageResult = new PageResult();
        Page<Competition> page = PageHelper.startPage(req.getPageNumber(), req.getPageSize());

        LambdaQueryWrapper<CompetitionJudge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(req.getCompetitionId()!=null,CompetitionJudge::getCompetitionId,req.getCompetitionId());

        List<CompetitionJudge> list = list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return pageResult;
        }

        // 查询用户
        List<CompetitionJudgeListRes> resList = handlerList(list);
        pageResult.setList(resList);
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    private List<CompetitionJudgeListRes> handlerList(List<CompetitionJudge> list) {
        if(CollectionUtils.isEmpty(list)){
            return Collections.EMPTY_LIST;
        }

        Set<Integer> userIdSet = list.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
        List<SysUser> sysUsers = sysUserService.listByIds(userIdSet);

        if(CollectionUtils.isEmpty(sysUsers)){
            return Collections.EMPTY_LIST;
        }
        Map<Integer, SysUser> userMap = sysUsers.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));

        List<CompetitionJudgeListRes> resList = new ArrayList<>(list.size());
        for (CompetitionJudge competitionJudge : list) {
            CompetitionJudgeListRes res = new CompetitionJudgeListRes();
            SysUser sysUser = userMap.get(competitionJudge.getUserId());
            if(sysUser!=null){
                res.setRealName(sysUser.getUserName());
            }
            res.setCompetitionId(competitionJudge.getCompetitionId());
            res.setUserId(competitionJudge.getUserId());
            resList.add(res);
        }

        return resList;
    }

    @Override
    public PageResult<Competition> page(CompetitionJudgeReq req) {
        LambdaQueryWrapper<CompetitionJudge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(req.getUserId()!=null, CompetitionJudge::getUserId, req.getUserId())
                .eq(req.getCompetitionId()!=null, CompetitionJudge::getCompetitionId, req.getCompetitionId())
                .eq(StringUtils.isNotBlank(req.getState()), CompetitionJudge::getState, req.getState());

        List<CompetitionJudge> judgeList = list(queryWrapper);

        if(CollectionUtils.isEmpty(judgeList)){
            return new PageResult();
        }

        PageResult<Competition> competitionPageResult = competitionService.queryList(new CompetitionReq() {{
            setCompetitionIdList(judgeList.stream().map(e->e.getCompetitionId()).collect(Collectors.toList()));
            setPageNumber(req.getPageNumber());
            setPageSize(req.getPageSize());
        }});
        return competitionPageResult;
    }

    @Override
    public void audit(CompetitionJudge competitionJudge) {
        LambdaUpdateWrapper<CompetitionJudge> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(CompetitionJudge::getCompetitionId,competitionJudge.getCompetitionId())
                .eq(CompetitionJudge::getUserId,competitionJudge.getUserId())
                .set(CompetitionJudge::getState,competitionJudge.getState());
        update(updateWrapper);
    }

    @Override
    public Boolean checkEnableJudge(CompetitionJudge competitionJudge) {
        LambdaQueryWrapper<CompetitionJudge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CompetitionJudge::getCompetitionId,competitionJudge.getCompetitionId())
                .eq(CompetitionJudge::getUserId,competitionJudge.getUserId());

        CompetitionJudge judge = getOne(queryWrapper);
        if(judge == null){
            throw new CoreException("该比赛不存在此评委");
        }

        if(!JudgeStateEnum.ENABLE.getCode().equals(judge.getState())){
            throw new CoreException("此评委在该比赛中未生效");
        }

        return true;
    }
}
